#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "log.hpp"

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port/ip[1024+]\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];

    // 创建客户端
    struct sockaddr_in client;
    unsigned int len = sizeof(client);
    bzero(&client, len);
    inet_pton(AF_INET, ip.c_str(), &(client.sin_addr));
    client.sin_family = AF_INET;
    client.sin_port = htons(port);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        lg(FATAL, "Socket error. errno:%d ,error", errno, strerror(errno));
        return 1;
    }

    if (connect(sockfd, (struct sockaddr *)&client, sizeof(client)) < 0)
    {
        lg(FATAL, "connect error. errno:%d ,error", errno, strerror(errno));
        return 1;
    }
    // OS自动bind
    
    while (true)
    {
       std::string message;

        std::cout << "Please Enter:  ";
        getline(std::cin, message);

        int n = write(sockfd, message.c_str(), message.size());

        char buffer[4096];
        ssize_t s = read(sockfd, &buffer, sizeof(buffer));
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
        
    }

    return 0;
}